package priv.mill.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.util.UrlEncoded;

import priv.mill.server.ToolServer;
import priv.mill.tool.Base64;

public class SortServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String code = req.getParameter("code");
		
		PrintWriter writer = resp.getWriter();
		resp.setHeader("Access-Control-Allow-Origin", "*");
		System.out.println(code);
		if(code.contains("import")) {
			writer.print("error");
			return;
		}
		long[] arr=new long[1000];
		for (int i = 0; i < arr.length; i++) {
			arr[i]=(long) (Math.random()*1000);
		}
		
		try {
			getResult("  package priv.mill.servlet;\n"+code,arr);
		} catch (Exception e) {
			e.printStackTrace();
		}
		for (int i = 1; i < arr.length; i++) {
			long temp=arr[i]-arr[i-1];
			if(temp<0) {
				writer.print("error");
				return;
			}
		}
		writer.print("success");
		
	}

	private void getResult(String code, long[] arr) throws Exception {
		Class<?> compile = ToolServer.compile("priv.mill.servlet.SortDemo", code);
		Method method = compile.getMethod("sort", long[].class);
		method.invoke(null, new Object[] {arr});
	}
}
